package com.bungarus.busi;

import com.bungarus.Access;
import com.bungarus.codec.protobuf.MessageProtobuf;
import com.bungarus.model.MessageBuilder;
import com.bungarus.model.MessageType;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

/**
 * Created by tang on 2018/11/19.
 */
public class ClientMessageRequestHandler extends ChannelInboundHandlerAdapter {
    private final Access access;

    public ClientMessageRequestHandler(Access access) {
        this.access = access;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(msg instanceof MessageProtobuf.Message){
            MessageProtobuf.Message message = (MessageProtobuf.Message)msg;
            if(MessageType.HEARTBEAT_PING == message.getHeader().getType()){
                ctx.writeAndFlush(MessageBuilder.buildHeartbeatPongMessage(message.getHeader().getId()));
            }
            else if(MessageType.ACK == message.getHeader().getType()){
                DischargeQueue queue = Discharger.getQueueInstance(Discharger.DISCHARGE_NAME_CLIENT);
                queue.removeFromQueue(Long.valueOf(message.getHeader().getId()));
            }
            else if(MessageType.IM == message.getHeader().getType()){ //send message to busi layer
                InnerClient backBusiNode = access.getInnerClientConnectingToBackendClusterNode(Access.CLUSTER_TAG_BUSI);
                backBusiNode.sendMessage(message, Access.CLUSTER_TAG_BUSI, ctx);
            }
            else if(MessageType.STATUS == message.getHeader().getType()) { //send message to transfer layer
                InnerClient transferNode = access.getInnerClientConnectingToBackendClusterNode(Access.CLUSTER_TAG_TRANSFER);
                transferNode.sendMessage(message, Access.CLUSTER_TAG_TRANSFER);
            }
        }
        else {
            super.channelRead(ctx, msg);
        }
    }
}
